package main

import (
	"bufio"
	"crypto/tls"
	"flag"
	"fmt"
	"net/http"
	"os"
	"sync"
	"time"

	"github.com/gorilla/websocket"
)

var (
	url string
	wg  sync.WaitGroup
)

func init() {
	flag.StringVar(&url, "url", "ws://localhost:19891/debug", "websocket server address")
}

func main() {
	flag.Parse()

	dialer := &websocket.Dialer{
		Proxy:            http.ProxyFromEnvironment,
		HandshakeTimeout: 45 * time.Second,
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
	}

	c, _, err := dialer.Dial(url, nil)
	if err != nil {
		fmt.Printf("Connected to %s, Error:%v\n\n", url, err)
		os.Exit(-1)
	}
	defer c.Close()

	fmt.Printf("Successfully Connected to %s\n\n", url)

	// recv
	go func() {
		wg.Add(1)
		defer wg.Done()
		for {
			_, msg, err := c.ReadMessage()
			if err != nil {
				fmt.Println("< recv an error,", err)
				return
			}
			fmt.Println("<", string(msg))
		}
	}()

	scanner := bufio.NewScanner(os.Stdin)

	// read
	fmt.Print("> ")
	for scanner.Scan() {
		err := c.WriteMessage(websocket.TextMessage, scanner.Bytes())
		if err != nil {
			fmt.Println("- write message error,", err)
			return
		}
		fmt.Print("> ")

	}
	wg.Wait()
}
